﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Web;
using System.Web.Mail;
using System.Web.Mvc;
using ZBJF.Warranty.WeiXinPayAPI;
using Senparc.Weixin.MP.TenPayLibV3;
using ZBJF.Warranty.Common.Common;
using Newtonsoft.Json;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.System;

namespace ZBJF.Warranty.H5.Controllers
{
    public class WeiXinPayController : Controller
    {
        #region 微信JsApi支付地址 + ActionResult JsApiPayPage(string orderId)
        /// <summary>
        /// 微信JsApi支付地址
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="successUrl">支付成功URL</param>
        /// <param name="cancelUrl">取消支付Url</param>
        /// <param name="errorUrl">支付出错Url</param>
        /// <returns></returns>
        [LoginFilter(IsCheck = false)]
        [WeiXinLoginFilter(CheckLogin = true)]
        public ActionResult JsApiPayPage(string orderId, string successUrl, string cancelUrl, string errorUrl)
        {
            ViewBag.orderId = orderId;
            ViewBag.successUrl = successUrl;
            ViewBag.cancelUrl = cancelUrl;
            ViewBag.errorUrl = errorUrl;
            LogHelper.WriteLog("调用统一支付地址！orderId：" + orderId, LogType.remark);

            //根据订单号orderID查询订单信息
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadByOrderNo(orderId);
            object openIdObj = Session["OpenId"];
            string openId = null;
            if (openIdObj == null)
            {
                if (HttpContext.Request.Url != null)
                {
                    var backUrl = HttpContext.Request.Url.ToString();
                    Session["BackUrl"] = backUrl;
                }
                return RedirectToAction("WxLogin", "WeiXin");
            }
            else
                openId = openIdObj.ToString();

            //预支付
            UnifiedorderResult prePayResult = JsApiPay.PrePay(string.Format("保险自助卡：【{0}】，订单号【{1}】支付", insuranceProductOrder.InsuranceProductName, orderId), openId, (int)(insuranceProductOrder.TotalPirce * 100), orderId);
            //预支付成功

            if (prePayResult != null && prePayResult.result_code == "SUCCESS" && prePayResult.return_code == "SUCCESS")
            {
                LogHelper.WriteLog("预支付成功！返回参数：" + JsonConvert.SerializeObject(prePayResult), LogType.remark);
                PayParamsModel model = JsApiPay.GetPayModel(prePayResult.prepay_id);
                ViewBag.model = model;
                LogHelper.WriteLog("生成支付信息：appid:" + model.AppID + ";TimeStamp:" + model.TimeStamp + ";NonceStr:" + model.NonceStr + ";Package:" + model.Package + ";SignType:" + model.SignType + ";SignType:" + model.PaySign + ";", LogType.remark);
                ViewBag.tag = JsonConvert.SerializeObject(model);
            }
            //预支付失败
            else
            {
                ViewBag.model = new PayParamsModel("111", "222");
                ViewBag.tag = "预支付失败";
                LogHelper.WriteLog("预支付失败！返回参数：" + JsonConvert.SerializeObject(prePayResult), LogType.remark);
            }

            return View();
        }
        #endregion

        #region 获取预支付信息 + ActionResult GetPrePayParams(string orderId)
        ///// <summary>
        ///// 获取预支付信息
        ///// </summary>
        ///// <param name="orderId">订单ID</param>
        ///// <returns></returns>
        //[HttpPost]
        //public JsonResult GetPrePayParams(string orderId)
        //{
        //    LogHelper.WriteLog("获取预支付信息开始！" , LogType.remark);
        //    //预支付
        //    UnifiedorderResult prePayResult = JsApiPay.PrePay("测试支付", "", 1,DateTime.Now.ToString("yyyyMMddhhmmss") );
        //    //预支付成功
        //    if (prePayResult != null && prePayResult.result_code == "SUCCESS" && prePayResult.return_code == "SUCCESS")
        //    {
        //        LogHelper.WriteLog("预支付成功！返回参数：" + JsonConvert.SerializeObject(prePayResult), LogType.remark);
        //        PayParamsModel model = JsApiPay.GetPayModel(prePayResult.prepay_id);
        //        return Json(new
        //        {
        //            Result = true,
        //            Data = model
        //        });
        //    }
        //    //预支付失败
        //    else
        //    {
        //        LogHelper.WriteLog("预支付失败！返回参数：" + JsonConvert.SerializeObject(prePayResult), LogType.remark);
        //        return Json(new
        //        {
        //            Result = false,
        //            Data = "预支付失败"
        //        });
        //    }
        //}
        #endregion

        #region 支付结果验证 + void PayResultValidate()
        [LoginFilter(IsCheck = false)]
        public void PayResultValidate()
        {
            LogHelper.WriteLog("支付结果验证开始！", LogType.remark);
            //验证支付结果
            PayResultNotify validateNotify = new PayResultNotify(System.Web.HttpContext.Current.Request);

            LogHelper.WriteLog("支付结果验证结束！返回参数：" + JsonConvert.SerializeObject(validateNotify), LogType.remark);
            //验证成功 
            if (validateNotify.ValidateIsSuccess)
            {
                //获取商家订单号
                string shopOrderNum = validateNotify.GetOrderNum();
                // 处理业务===============================Start
                bool result = true;//业务结果

                var order = ServiceFactory.InsuranceProductOrderServiceInstance.LoadByOrderNo(shopOrderNum);
                if (order.Status == (byte)InsuranceProductOrderStatus.PendingPayment) //当前是待支付状态的才去更新状态和创建卡密或者生成保单，避免重复调用
                {
                    result = ServiceFactory.InsuranceProductOrderServiceInstance.PayOrderAndCreateCard(shopOrderNum);
                    try
                    {
                        #region 发送短信
                        var msg = string.Empty;
                        ServiceFactory.SendSmsVerificationCodeLogServiceInstance.SendSMS(order.BuyUserPhone, VerificationCodeTemp.SMS_120375456.ToString(), order.BuyUserName,
                        ref msg);
                        #endregion

                        #region 发送邮件
                        var mail = new MailHelper();
                        //下载邮件内容
                        var emailContent = WebApiCaller.GetHtmlSourceCode("http://m.zhongbaojinfu.com.cn/InsuranceProductOrder/EmailTemplate/" + order.ID);
                        emailContent = emailContent.Replace("src=\"", "src=\"http://m.zhongbaojinfu.com.cn");
                        emailContent = emailContent.Replace("url(", "url(http://m.zhongbaojinfu.com.cn");

                        var attachmentList = new List<System.Web.Mail.MailAttachment>();

                        #region HTML
                        var htmlFile = string.Format("{0}{1}({2}).html", Server.MapPath("/"), order.InsuranceProductName, order.OrderNo);
                        System.IO.File.AppendAllText(htmlFile, emailContent);
                        System.Web.Mail.MailAttachment data = new System.Web.Mail.MailAttachment(htmlFile);
                        attachmentList.Add(data);
                        #endregion

                        #region PDF

                        var bytes = new PechkinPDF().ConvertUrlToBytes("http://m.zhongbaojinfu.com.cn/InsuranceProductOrder/EmailTemplate/" + order.ID, 24);

                        var pdfFile = string.Format("{0}{1}({2}).pdf", Server.MapPath("/"), order.InsuranceProductName, order.OrderNo);
                        //1.必须先转为pdf文件
                        var fileContents = File(bytes, "application/pdf", pdfFile);
                        var fileContentsBytes = fileContents.FileContents;
                        //2.再把pdf文件流程写入到文件中
                        FileStream fs = new FileStream(pdfFile, FileMode.Create);
                        fs.Write(fileContentsBytes, 0, fileContentsBytes.Length);
                        fs.Close();
                        System.Web.Mail.MailAttachment dataPdf = new System.Web.Mail.MailAttachment(pdfFile);
                        attachmentList.Add(dataPdf);
                        #endregion

                        #region 条款
                        var termFile = string.Format("{0}", Server.MapPath("/Attachments/中保金服手机碎屏保障服务合同条款.docx"));
                        System.Web.Mail.MailAttachment termData = new System.Web.Mail.MailAttachment(termFile);
                        attachmentList.Add(termData);
                        #endregion
                        mail.Attachments = attachmentList;

                        mail.SendMail(order.BuyUserEmail, "", "您已成功购买服务保障卡，请及时下载卡密，激活服务保障", emailContent);
                        Thread.Sleep(10000);
                        System.IO.File.Delete(htmlFile);
                        System.IO.File.Delete(pdfFile);
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            LogHelper.WriteLog(string.Format("异常位置: {0};异常信息:{1};错误源:{2};堆栈信息:{3}", "SendMailError", ex.Message, ex.Source, ex.StackTrace), LogType.error);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                // 处理业务===============================End
                if (!result) //处理失败
                {
                    validateNotify.SetResponseContent(ReturnCodeEnum.FAIL, "更新订单状态失败");
                }

            }
            LogHelper.WriteLog("响应微信的参数：" + validateNotify.GetResponseContent(), LogType.remark);
            Response.Write(validateNotify.GetResponseContent());
            Response.End();
        }
        #endregion

    }
}